package com.wwwarehouse.taskcenter.fragment.job_point.step7;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.JobPointSetRuleResponseBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;
import com.wwwarehouse.taskcenter.constant.job_point.TaskCenterCommon;
import com.wwwarehouse.taskcenter.eventbus_event.TaskPointCardEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.wwwarehouse.taskcenter.fragment.job_point.AddJobPointCardFragment.KEY_BUSINESS_ID;
import static com.wwwarehouse.taskcenter.fragment.job_point.AddJobPointCardFragment.KEY_JOB_POINT_UKID;

/**
 * Created by Jackie on 2017/11/13.
 * 设置作业点规则
 */

public class SetJobPointRuleFragment extends BaseFragment implements View.OnClickListener {
    private View mRootView;

    private ImageView mStartImg;

    private LinearLayout mStartNewLineLayout;

    private LinearLayout mStartDetailsLayout;

    private Button mStartDetailsBtn;
    private Button mStartResetBtn;

    private Button mSaveBtn;

    private String mBusinessId;
    private String mJobPointUkid;

    private SetJobPointRuleReceiver mReceiver;

    private ArrayList<JobPointSetRuleResponseBean.JobPointRuleDetailsBean> mJobPointRuleDetailsList;

    public static final String KEY_SET_JOB_POINT_LIST = "key_set_job_point_list";

    private static final int REQUEST_RELATE_RULE = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_set_job_point_rule, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mStartImg = findView(mRootView, R.id.iv_plus_start);

        mStartNewLineLayout = findView(mRootView, R.id.flex_layout_start);

        mStartDetailsLayout = findView(mRootView, R.id.ll_details_start);

        mStartDetailsBtn = findView(mRootView, R.id.btn_details_start);
        mStartResetBtn = findView(mRootView, R.id.btn_reset_start);

        mSaveBtn = findView(mRootView, R.id.btn_save);

        mReceiver = new SetJobPointRuleReceiver();

        mActivity.registerReceiver(mReceiver, new IntentFilter("ChooseJobPointRule"));
    }

    private void initData() {
        TaskCenterCommon.getInstance().setDetails(false);

        Bundle bundle = getArguments();

        if (bundle != null) {
            mBusinessId = bundle.getString(KEY_BUSINESS_ID);
            mJobPointUkid = bundle.getString(KEY_JOB_POINT_UKID);
        }
    }

    private void initEvent() {
        mStartImg.setOnClickListener(this);

        mStartDetailsBtn.setOnClickListener(this);
        mStartResetBtn.setOnClickListener(this);

        mSaveBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.iv_plus_start) {
            TaskCenterCommon.getInstance().setDetails(false);

            Bundle bundle = new Bundle();
            bundle.putString(KEY_BUSINESS_ID, mBusinessId);

            ChooseJobPointRuleFragment chooseJobPointRuleFragment = new ChooseJobPointRuleFragment();
            chooseJobPointRuleFragment.setArguments(bundle);
            pushFragment(chooseJobPointRuleFragment);
        } else if (id == R.id.btn_details_start) {
            TaskCenterCommon.getInstance().setDetails(true);

            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList(KEY_SET_JOB_POINT_LIST, mJobPointRuleDetailsList);

            ChooseJobPointRuleFragment chooseJobPointRuleFragment = new ChooseJobPointRuleFragment();
            chooseJobPointRuleFragment.setArguments(bundle);
            pushFragment(chooseJobPointRuleFragment);
        } else if (id == R.id.btn_reset_start) {
            mStartNewLineLayout.removeAllViews();

            mStartImg.setVisibility(View.VISIBLE);
            mStartDetailsLayout.setVisibility(View.GONE);

            mSaveBtn.setEnabled(false);
        } else if (id == R.id.btn_save) {
            relateRule();
        }
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof SetJobPointRuleFragment) {
            mActivity.setTitle(R.string.set_job_point_rule);
        }
    }

    @Override
    public void requestDatas() {

    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_RELATE_RULE:
                    if ("0".equals(commonClass.getCode())) {
                        popFragment();

                        //第七步完成
                        TaskPointCardEvent taskPointCardEvent = new TaskPointCardEvent();
                        taskPointCardEvent.setFinish7(true);

                        EventBus.getDefault().post(taskPointCardEvent);
                    } else {
                       toast(commonClass.getMsg());
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String s, int i) {

        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };

    /**
     * 关联作业点规则
     */
    private void relateRule() {
        showProgressDialog();

        Map map = new HashMap();

        map.put("jobPointUkid", mJobPointUkid);

        List<Map<String, String>> list = new ArrayList<>();

        for (JobPointSetRuleResponseBean.JobPointRuleDetailsBean jobPointRuleDetailsBean : mJobPointRuleDetailsList) {
            Map<String, String> listMap = new HashMap<>();

            listMap.put("key", jobPointRuleDetailsBean.getTempInstanceId());
            listMap.put("value", jobPointRuleDetailsBean.getTempInatanceName());

            list.add(listMap);
        }

        map.put("tempInstanceIds", list);

        NoHttpUtils.httpPost(TaskCenterConstant.URL_RELATE_RULE, map, mOnResponseListener, REQUEST_RELATE_RULE);
    }

    private class SetJobPointRuleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if ("ChooseJobPointRule".equals(action)) {
                Bundle bundle = intent.getExtras();
                mJobPointRuleDetailsList = bundle.getParcelableArrayList(KEY_SET_JOB_POINT_LIST);

                mStartNewLineLayout.removeAllViews();

                if (mJobPointRuleDetailsList != null && mJobPointRuleDetailsList.size() > 0) {
                    mStartImg.setVisibility(View.GONE);
                    mStartDetailsLayout.setVisibility(View.VISIBLE);

                    mSaveBtn.setEnabled(true);

                    // 小于5行，显示完全，大于5行，第6行显示......
                    if (mJobPointRuleDetailsList.size() <= 5) {
                        for (JobPointSetRuleResponseBean.JobPointRuleDetailsBean jobPointDetailsBean : mJobPointRuleDetailsList) {
                            TextView textView = new TextView(mActivity);
                            textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                            textView.setSingleLine();
                            textView.setEllipsize(TextUtils.TruncateAt.END);
                            textView.setGravity(Gravity.CENTER);
                            Drawable leftDrawable = mActivity.getResources().getDrawable(R.drawable.rule_point);
                            leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
                            textView.setCompoundDrawablePadding(ConvertUtils.dip2px(mActivity, 6));
                            textView.setCompoundDrawables(leftDrawable, null, null, null);
                            textView.setText(jobPointDetailsBean.getTempInatanceName());
                            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                            textView.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));

                            mStartNewLineLayout.addView(textView);

                            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams();
                            params.topMargin = ConvertUtils.dip2px(mActivity, 10);
                            textView.setLayoutParams(params);
                        }
                    } else {
                        for (int i = 0; i < 5; i++) {
                            TextView textView = new TextView(mActivity);
                            textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                            textView.setSingleLine();
                            textView.setEllipsize(TextUtils.TruncateAt.END);
                            textView.setGravity(Gravity.CENTER);
                            Drawable leftDrawable = mActivity.getResources().getDrawable(R.drawable.rule_point);
                            leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
                            textView.setCompoundDrawablePadding(ConvertUtils.dip2px(mActivity, 6));
                            textView.setCompoundDrawables(leftDrawable, null, null, null);
                            textView.setText(mJobPointRuleDetailsList.get(i).getTempInatanceName());
                            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                            textView.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));

                            mStartNewLineLayout.addView(textView);

                            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams();
                            params.topMargin = ConvertUtils.dip2px(mActivity, 10);
                            textView.setLayoutParams(params);
                        }

                        TextView textView = new TextView(mActivity);
                        textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        textView.setSingleLine();
                        textView.setEllipsize(TextUtils.TruncateAt.END);
                        textView.setGravity(Gravity.CENTER);
                        Drawable leftDrawable = mActivity.getResources().getDrawable(R.drawable.rule_point);
                        leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
                        textView.setCompoundDrawablePadding(ConvertUtils.dip2px(mActivity, 6));
                        textView.setCompoundDrawables(leftDrawable, null, null, null);
                        textView.setText("……");
                        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                        textView.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));

                        mStartNewLineLayout.addView(textView);

                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams();
                        params.topMargin = ConvertUtils.dip2px(mActivity, 10);
                        textView.setLayoutParams(params);
                    }
                } else {
                    mStartImg.setVisibility(View.VISIBLE);
                    mStartDetailsLayout.setVisibility(View.GONE);

                    mSaveBtn.setEnabled(false);
                }
            }
        }
    }
}
